<template>
  <div>
    <h3>编辑用户</h3>
    <form>
      <div class="form-row">
        <div class="form-group col-md-4">
          <label for="name">姓名</label>
          <input type="text" v-model="user.name" class="form-control" id="name" placeholder="name">
        </div>
        <div class="form-group col-md-4">
          <label for="age">年龄</label>
          <input type="number" v-model="user.age" class="form-control" id="age" placeholder="age">
        </div>
        <div class="form-group col-md-4">
          <label for="gender">性别</label>
          <select id="gender" class="form-control" v-model="user.gender">
            <option selected>男</option>
            <option>女</option>
          </select>
        </div>
      </div>
      <input type="button" @click="updateUserInfo()" class="btn btn-primary" value="保存"/>
      <a href="#/user" class="btn btn-danger">取消</a>
    </form>
  </div>
</template>

<script>
  export default {
    name: "UserEdit",
    data() {
      return ({
        user: {
          id: '',
          name: '',
          age: undefined,
          gender: ''
        },
        msg: ''
      });
    },
    methods: {
      //更新用户信息
      updateUserInfo() {
        this.$http.put(this.$api + "/user/", this.user).then((response) => {//这里必须使用箭头函数，否则this将为undefined
          //success是在后端定义的响应数据的key，其值为true/false
          this.msg = response.data.msg
          if (response.data.success) {
            this.$router.push("/user");//切换路由，用于隐藏添加页面
          }
        })
      },
      findById() {
        this.$http.get(this.$api + "/user/" + this.user.id).then((res)=>{
          this.user = res.data
        })
      }
    },
    created() {
      this.user.id = this.$route.params.id
      this.findById()
    },
    watch:{
      //监听路由的变化，用于实时更新当前修改用户的信息
      $route:{
        handler:function (newRoute) {
          //检测新的路由是不是以/user/edit开头，等于0说明在开头就匹配上了
          if (newRoute.path.indexOf('/user/edit') === 0){
            this.user.id = this.$route.params.id
            this.findById()
          }
        }
      }
    }
  }
</script>

<style scoped>

</style>